package com.k2data.k2app.service.pas14;


import com.k2data.k2app.common.K2Assert;
import com.k2data.k2app.domain.pas14.job.Pas14Job;
import com.k2data.k2app.util.JsonUtils;
import com.k2data.k2app.util.PasHttpUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 从pas取回来的数据
 * Created by clb on 17-3-30.
 */
@Log4j2
@Service
public class Pas14JobService extends Pas14Basic {
	/**
	 * 删除作业
	 * @param projectId 项目id
	 * @param jobId 作业id
	 * @return
	 * @throws Exception
	 */
	public Long delete(Long projectId,Long jobId) throws Exception{
		String infoError = PasHttpUtil.onDelete(getJobsUrl()+"?projId="+projectId+"&jobId="+jobId);
		Map<String, Object> resultMap = JsonUtils.convertJsonStrToMap(infoError);
		K2Assert.isExceptionByPas(resultMap);
		return jobId;
	}

	/**
	 * id查询
	 * 因为list和get查的接口数据不一样，为了保持一直，调用list接口
	 * @return Instance
	 * @throws Exception
	 */
	public Pas14Job get(Long jobId) throws Exception {
		Map<String,Long> param = new HashMap<>();
		param.put("id",jobId);
		List<Pas14Job> pas14Jobs = listByParam(param);
		if(pas14Jobs.size()>0){
			Pas14Job pas14Job = pas14Jobs.get(0);
			return pas14Job;
		}
		return null;
	}

	/**
	 *  <p>查询所有</p>
	 *  <P>按照owner过滤</p>
	 * @return list
	 * @throws Exception
	 */
	public List<Pas14Job> list() throws Exception {
		Map<String,String> param = new HashMap<>();
		return listByParam(param);
	}

	/**
	 * 条件查询
	 * @param param
	 * @return
	 * @throws Exception
	 */
	public List<Pas14Job> listByParam(Map param) throws Exception {
		String infoError = PasHttpUtil.onGet(String.format("%s?%s",getJobsUrl(),getQueryCondition(param)));
		Map<String, Object> resultMap = JsonUtils.convertJsonStrToMap(infoError);
		K2Assert.isExceptionByPas(resultMap);
		List list = JsonUtils.convertJsonStrToList(resultMap.get("result").toString());
		List<Pas14Job> pas14Jobs = new ArrayList<>();
		for(int i =0;i<list.size();i++){
			Pas14Job pas14Job = (Pas14Job)JsonUtils.JSONToObj(list.get(i).toString(), Pas14Job.class);
			pas14Jobs.add(pas14Job);
		}
		return pas14Jobs;
	}
}
